package chapter9;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.List;
import java.util.Map;
import java.util.Properties;

import static java.util.stream.Collectors.toList;


/**
 * 根据topic来查询kafka的起始offset和 最新的offset
 * beginningOffsets: {wang-0=0, wang-1=0, wang-2=0}
 * endOffsets:  {wang-0=28, wang-1=32, wang-2=32}
 */
public class CheckBeginingOffsetAndEndOffset {
    public static void main(String[] args) {
        KafkaConsumer<String, String> kafkaConsumer = createNewConsumer();
        List<PartitionInfo> partitions = kafkaConsumer.partitionsFor("wang");
        List<TopicPartition> tpList = partitions.stream()
                .map(pInfo -> new TopicPartition(pInfo.topic(), pInfo.partition()))
                .collect(toList());
        Map<TopicPartition, Long> beginningOffsets =
                kafkaConsumer.beginningOffsets(tpList);
        Map<TopicPartition, Long> endOffsets = kafkaConsumer.endOffsets(tpList);


        System.out.println("beginningOffsets: " + beginningOffsets);
        System.out.println("endOffsets:  " + endOffsets);


    }

    public static KafkaConsumer<String,String> createNewConsumer() {
        Properties props = new Properties();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "192.168.52.100:9092");
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "group.demo");
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
                StringDeserializer.class.getName());
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
                StringDeserializer.class.getName());
        return new KafkaConsumer<>(props);
    }
}
